package com.junjie.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TimeUtils {

    public static void main(String[] args) throws ParseException {
        int age = getAgeByBirth("yyyy-MM-dd", "1996-09-11");
        System.out.println(age);
    }

    //根据生日计算出当前的年纪
    public static int getAgeByBirth(String timeType, String birth) throws ParseException {
        Date birthday = new SimpleDateFormat(timeType).parse(birth);
        Calendar now = Calendar.getInstance();
        Calendar b = Calendar.getInstance();
        b.setTime(birthday);
        int year = now.get(Calendar.YEAR) - b.get(Calendar.YEAR);
        int month = now.get(Calendar.MONTH) - b.get(Calendar.MONTH);
        int day = now.get(Calendar.DAY_OF_MONTH) - b.get(Calendar.DAY_OF_MONTH);
        if (month < 0) {
            month = 12 + month;
            if(day < 0) day = - day;
            year--;
        } else if (day < 0) {
            day = - day;
            year --;
        }
        System.out.println(year + "-" + month + "-" + day);
        return year;
    }
}
